const {
	Service
} = require('uni-cloud-router');
const {
	parser,
	success,
	exception,
	error,
	typeOf,
	Clock,
	timingLogger,
	StatusEnum,
	isNumber
} = require("lg-utils");
const {
	pushLineitem,
	popLineitem
} = require("lg-utils-db");
const db = uniCloud.database();
const dbCmd = db.command;
const DATA_DICTIONARY_COLL = db.collection("data-dictionary");
module.exports = class CommonService extends Service {
	async xxx() {
		try {
			return "xxxxxxx"
		} catch (e) {
			throw e
		}

	}

	async updateIterDate({
		where = {},
		data = ""
	} = {}) {
		try {
			 const {updated} = await pushLineitem({
				where,
				collection: DATA_DICTIONARY_COLL,
				line: "data",
				list: data
			});
			
			if(isNumber(updated) && updated > 0){
				 return success(updated); 
			}else{
				return error("更新字典项data列表请求异常;",{updated});
			}
		} catch (e) {
			throw e
		}

	}

	async updateIterPushDateByType({
		type = "",
		data = []
	} = {}) {
		try {
		  const	{updated } =  await pushLineitem({
				where: {
					type
				},
				collection: DATA_DICTIONARY_COLL,
				line: "data",
				list: data
			}) || {};
			
			if(isNumber(updated) && updated > 0){
				 return success(updated); 
			}else{
				return error("更新字典项data列表请求异常;",{updated});
			}
			
		} catch (e) {
			throw e
		}

	}
	async updateIterPopDateByType({
		type = "stockSymbolList",
		num = 1
	} = {}) {
		try {
			const promises = [];
			for (let i = 0; i < num; i++) {
				promises.push(
				    popLineitem({
						where: {
							type
						},
						collection: DATA_DICTIONARY_COLL,
						line: "data",
					})
				);
			}

		 return	await Promise.all(promises).then(res => {
				// [{"affectedDocs":1,"updated":1}]
				let updatedCount = 0;
				let updatedFailCount = 0;
				let updatedAllSuccStatus = false;
				res.forEach( eachIter => {
					 const {updated} =  eachIter || {};
					 if(typeOf(updated,StatusEnum.NUMBER) && updated > 0){
						 updatedCount ++;
					 }else{
						 updatedFailCount ++;
					 }
					 
					 
				})
				if(!updatedFailCount){
					updatedAllSuccStatus = true;
				}
				return success({updatedCount,updatedFailCount,updatedAllSuccStatus}); 
			}).catch(err => {
				return error(err);
			}).finally(() => {

			});


		} catch (e) {
			throw e
		}

	}


	async addDictDataItem(iters = []) {
		try {
			console.log(iters);
			if (iters && iters.length) {
				return await DATA_DICTIONARY_COLL.add(iters);
			} else {
				return error("插入无效的值;", iters);
			}
		} catch (e) {
			throw e
		}

	}
	async getDictDataByWhere(where = {}) {
		try {
			return await DATA_DICTIONARY_COLL.where(where).get();
		} catch (e) {
			throw e
		}

	}

	async getDictDataByType(
		type = ""
	) {
		try {
			return await DATA_DICTIONARY_COLL.where({
				type
			}).get();
		} catch (e) {
			throw e
		}

	}


}
